package com.yunda.nebula.gateway.listener.nacos;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.google.gson.JsonObject;
import com.yunda.nebula.gateway.core.entity.ConfigData;
import com.yunda.nebula.gateway.service.ITbGatewayAppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

public class NacosConfigRefresh implements ApplicationListener<ApplicationReadyEvent> {

    private AtomicBoolean ready = new AtomicBoolean(false);

    private ITbGatewayAppService appService;

    private NacosConfigProperties nacosConfigProperties;

    public NacosConfigRefresh(ITbGatewayAppService appService, NacosConfigProperties nacosConfigProperties) {
        this.appService = appService;
        this.nacosConfigProperties = nacosConfigProperties;
    }


    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {

        if (this.ready.compareAndSet(false, true)) {
            this.initNacosConfig();
        }

    }

    private void initNacosConfig() {
        ConfigService configService = nacosConfigProperties.configServiceInstance();
        try {
            String config = configService.getConfig("chq-jc-gateway-appid", nacosConfigProperties.getGroup(), 100000L);
            List<String> appids = appService.listApps();
            if (!CollectionUtils.isEmpty(appids)) {

                if (!JSONObject.toJSON(appids).equals(config)) {
                    configService.publishConfig("chq-jc-gateway-appid", nacosConfigProperties.getGroup(), JSONObject.toJSONString(appids));
                }

                for (String appid : appids) {
                    ConfigData configData = appService.fetch(appid);
                    if (Objects.nonNull(configData)) {
                        try {
                            configService.publishConfig("chq-jc-gateway-" + appid, nacosConfigProperties.getGroup(), JSONObject.toJSONString(configData));
                        } catch (NacosException ex) {

                        }
                    }
                }

            }
        } catch (Exception e) {

        }


    }
}
